$(function () {
    $("#sysUserGrid").Grid({
        url: '../sys/user/list',
        colModel: [
            {label: '用户ID', name: 'userId', index: "user_id", key: true, hidden: true},
            {label: '用户名', name: 'userName', index: "user_id", width: 75},
            {label: '用户姓名', name: 'nickName', index: "user_id", width: 75},
            {label: '所属部门', name: 'deptName', index: "dept_id", width: 75},
            {
                label: '是否是领导', name: 'leader', index: "leader", width: 75, formatter: function (value) {
                    return sysEnums.IS_LEADER[value];
                }
            },
            {
                label: '状态', name: 'status', width: 80, formatter: function (value) {
                    return value === 0 ?
                        '<span class="label label-danger">禁用</span>' :
                        '<span class="label label-success">正常</span>';
                }
            },
            {
                label: '特种人员', name: 'special', width: 80, formatter: function (value) {
                    return value === 0 ?
                        '<span class="label label-danger">否</span>' :
                        '<span class="label label-success">是</span>';
                }
            },
            {
                label: '附件', width: 80, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    if (row.special === 1) {
                        return "<button class='btn btn-outline btn-info' onclick='vm.goFileUpload(\"" + row.id + "\")'><i class='fa fa-upload'></i>&nbsp;上传</button>";
                    } else {
                        return "<button class='btn btn-outline btn-info' ><i class='fa fa-info'></i>&nbsp;无需附件</button>";
                    }

                }
            },
            {
                label: '复审记录', width: 80, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    if (row.special === 1) {
                        return "<button class='btn btn-outline btn-info' onclick='vm.addCheck(\"" + row.id + "\")'><i class='fa fa-info'></i>&nbsp;复审记录</button>";
                    } else {
                        return "<button class='btn btn-outline btn-info' ><i class='fa fa-info'></i>&nbsp;无复审记录</button>";
                    }
                }
            },
            {
                label: '创建时间', name: 'createTime', index: "create_time", width: 80,
                formatter: function (value) {
                    return transDate(value);
                }
            }]
    });
    vm.getTreeList();
    vm.getStore();
});
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
//车间组织数
var deptSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "complexName"
        }
    },
    callback: {
        beforeCheck: true,
        beforeClick: outTreeCheck
    }
};
function outTreeCheck(e, treeObj, treeNode) {
    vm.q.deptId = treeObj.deptId;
    vm.query();
}
var ztree;

var vm = new Vue({
    el: '#sysUser',
    data: {
        q: {
            userName: null,
            nickName: null,
            special: '',
            deptId:''
        },
        showList: true,
        title: null,
        roleList: {},
        readonly: false, // 是否是更新，控制用户名字段制度
        user: {
            status: 1,
            special: 0,
            leader: 0,
            deptName: '',
            roleIdList: []
        },
        treeList: [],
        specUserRecord: {
            checkResult: 1,
        },
        ruleValidate: {
            userName: [
                {required: true, message: '账号不能为空', trigger: 'blur'}
            ],
            nickName: [
                {required: true, message: '姓名不能为空', trigger: 'blur'}
            ],
            deptName: [
                {required: true, message: '部门不能为空', trigger: 'blur'}
            ]
        },
        leaderArray: enumsToList("IS_LEADER"),
    },
    methods: {
        //加载列表页树
        getStore: function () {
            deptZtree = $.fn.zTree.init($("#storeTree"), deptSetting, vm.treeList);
            // 默认展开工厂一级
            deptZtree.expandNode(deptZtree.getNodeByParam("deptId",'01',null));
            //deptZtree.expandAll(true);
        },
        getTreeList: function () {
            Ajax.request({
                url: '../sys/user/treeDeptBySCXLevel?level=2',
                async: false,
                successCallback: function (r) {
                    vm.treeList = r.list;
                }
            });
        },
        resetLoginTimes: function () {
            var selectedUser = getSelectedRowData('#sysUserGrid');
            if (!selectedUser) {
                return;
            }
            Ajax.request({
                url: '../sys/user/resetLoginTimes/' + selectedUser.userName,
                type: 'POST',
                successCallback: function (res) {
                    alert('重置登录次数成功！');
                }
            });
        },
        goFileUpload: function (id) {
            openWindow({
                type: 2,
                title: '<i class="fa fa-upload"></i> 上传附件',
                content: '../sys/userFile.html?userId=' + id
            })
        },
        query: function () {
            vm.reload();
        },
        check: function () {
            var data = getSelectedRowData("#sysUserGrid");

            if (data.userId == null) {
                return;
            }
            if (data.spec === '0') {
                alert('请选择特种人员');
                return;
            }
            vm.specUserRecord = {'userId': data.userId}
            openWindow({
                title: "确认复审",
                area: ['350px', '250px'],
                content: jQuery("#reviewLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: '../specuserrecord/save',
                        params: JSON.stringify(vm.specUserRecord),
                        contentType: "application/json",
                        type: 'POST',
                        successCallback: function (res) {
                            alert('审核成功!');
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        }
                    });
                }
            });
        },
        addCheck: function (id) {
            openWindow({
                type: 2,
                title: '<i class="fa fa-anchor"></i> 复审记录',
                content: '../sys/specuserrecord.html?userId=' + id
            });
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增(默认密码：888888)";
            vm.readonly = false;
            vm.roleList = {};
            vm.user = {status: 1, special: 0, roleIdList: [], deptId: '', deptName: '', leader: 0};

            //获取角色信息
            this.getRoleList();
            vm.getDept();
        },
        getDept: function () {
            //加载部门树
            Ajax.request({
                url: '../sys/dept/list?flag=1',
                async: false,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#deptTree"), setting, r.list);
                    var node = ztree.getNodeByParam("deptId", vm.user.deptId);
                    if (node != null) {
                        ztree.selectNode(node);
                        vm.user.deptName = node.name;
                    }
                }
            });
        },
        update: function () {
            var user = getSelectedRowData("#sysUserGrid");
            if (user.userId == null) {
                return;
            }
            vm.readonly = true;
            vm.showList = false;
            vm.title = "修改";
            Ajax.request({
                url: "../sys/user/info/" + user.userId,
                async: false,
                successCallback: function (r) {
                    vm.user = r.user;
                    //获取角色信息
                    vm.getRoleList();
                    vm.getDept();
                }
            });

        },
        del: function () {
            var userIds = getSelectedRows("#sysUserGrid");
            if (userIds == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../sys/user/delete",
                    params: JSON.stringify(userIds),
                    contentType: "application/json",
                    type: 'POST',
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.user.userId == null ? "../sys/user/save" : "../sys/user/update";
            var params = JSON.stringify(vm.user);
            Ajax.request({
                url: url,
                params: params,
                contentType: "application/json",
                type: 'POST',
                successCallback: function () {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        getRoleList: function () {
            Ajax.request({
                url: '../sys/role/select',
                async: false,
                successCallback: function (r) {
                    vm.roleList = r.list;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            // 清空postData缓存数据
            var postData = $("#sysUserGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var page = $("#sysUserGrid").jqGrid('getGridParam', 'page');
            $("#sysUserGrid").jqGrid('setGridParam', {
                postData: {'userName': vm.q.userName, 'nickName': vm.q.nickName, 'special': vm.q.special,'deptId':vm.q.deptId},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                userName: '',
                special: '',
                deptId:''
            }
            deptZtree.cancelSelectedNode();
            vm.reload();
        },
        deptTree: function () {
            openWindow({
                title: "选择部门",
                area: ['300px', '450px'],
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级部门
                    vm.user.deptId = node[0].deptId;
                    vm.user.deptName = node[0].name;

                    layer.close(index);
                }
            });
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                iview.Message.success('文件上传成功');
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        }
    }
});
